﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.IO;

namespace QuailDashboard.View.Web
{
    public class QuailTestExecution
    {

        static Process _seleniumProcess = null;
        private int _seleniumPort;
        public bool ExecuteTests(List<string> testNames)
        {
            _seleniumProcess = null;
            try
            {
                if (CheckAvailableTcpPort(4444))
                {
                    _seleniumProcess = StartSeleniumRc();
                }
                StartGallio(testNames);
                if (_seleniumProcess != null)
                {
                    Uri seleniumShutdown = new Uri("http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer");
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(seleniumShutdown);
                    HttpWebResponse resp = (HttpWebResponse) req.GetResponse(); 

                }
                return true;
            }
                
            catch (Exception)
            {

                return false;
            }
        }

        private bool StartGallio(List<string> testNames)
        {
            if (testNames.Count > 0)
            {
                var proc = new Process();
                string testDllFolder = Properties.Settings.Default.TestDllFolder;
                string gallioFolder = Properties.Settings.Default.GallioContentFolder;
                string[] testParts = testNames[0].Split('.');
                string dllName = testParts[0] + "\\bin\\Debug\\" + testParts[0];
                string testNamesForGallio = testParts[testParts.GetUpperBound(0)];
                testNames.Remove(testNames[0]);
                for (int i = 0; i < testNames.Count; i++)
                {
                    testParts = testNames[i].Split('.');
                    testNamesForGallio = string.Format("{0},{1}", testNamesForGallio, testParts[testParts.GetUpperBound(0)]);
                }
                string gallioStartUpConfigFileName = string.Format(@"{0}GallioStartupConfig{1:MMddyyyy_HHmmss}.txt", testDllFolder,DateTime.Now);
                StreamWriter gallioStartUpConfig = CreateGallioStartupConfig(gallioStartUpConfigFileName,testDllFolder, dllName,testNamesForGallio);
                gallioStartUpConfig.Close();
                var psi =
                    new ProcessStartInfo(string.Format(@"{0}\gallio.echo.exe", gallioFolder),
                                         string.Format(@"@{0}", gallioStartUpConfigFileName))
                    {
                        RedirectStandardOutput = false,
                        WindowStyle = ProcessWindowStyle.Normal,
                        UseShellExecute = true,
                    };

                Debug.WriteLine(string.Format("{0} {1}",psi.FileName, psi.Arguments));
                proc.StartInfo = psi;

                proc.Start();

                proc.WaitForExit();
                int exitCode = proc.ExitCode;

                proc.Close();
                File.Delete(gallioStartUpConfigFileName);
            }
            return true;

        }


        private StreamWriter CreateGallioStartupConfig(string gallioStartUpConfigFileName, string testDllFolder, string dllName, string testNamesForGallio)
        {
            StreamWriter gallioStartUpConfig =
                File.CreateText(gallioStartUpConfigFileName);
            gallioStartUpConfig.WriteLine(string.Format(@"{0}\{1}.dll", testDllFolder, dllName));
            gallioStartUpConfig.WriteLine("/f:Member:{0}", testNamesForGallio);
            gallioStartUpConfig.WriteLine("/v:Quiet");
            gallioStartUpConfig.WriteLine("/rtl:1000");
            gallioStartUpConfig.WriteLine("/rd:C:\\AutomationTestLogs");
            gallioStartUpConfig.WriteLine("/rt:Xml-Inline");
            return gallioStartUpConfig;
        }

        private static Process StartSeleniumRc()
        {
            _seleniumProcess = new Process();

            string seleniumFolder = Properties.Settings.Default.SeleniumContentFolder;
            //string seleniumFolder = "cmd C:\\SAJPrimary\\Branches\\release_7.2\\QualityAssurance\\SeleniumObjects\\selenium-remote-control-1.0.1\\selenium-server-1.0.1\\runserver.bat";
            //    "c:\\pstools\\psexec  -i cmd /c C:\\SAJPrimary\\Branches\\release_7.2\\QualityAssurance\\SeleniumObjects\\selenium-remote-control-1.0.1\\selenium-server-1.0.1\\runserver.bat";
            var psi =
                new ProcessStartInfo(string.Format(@"{0}\runserver.bat", seleniumFolder))
//                new ProcessStartInfo(string.Format(@"{0}", seleniumFolder))
                {
                    RedirectStandardOutput = false,
                    WindowStyle = ProcessWindowStyle.Normal,
                    UseShellExecute = true,
                    WorkingDirectory= seleniumFolder
                };
            _seleniumProcess.StartInfo = psi;

            _seleniumProcess.Start();
            return _seleniumProcess;
        }

        private bool CheckAvailableTcpPort(int startingPortNumber)
        {
            int portToCheck = startingPortNumber;
            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndpoints = ipGlobalProperties.GetActiveTcpListeners();
            bool isAvailable = false;

            isAvailable = true;
            foreach (IPEndPoint tcpi in ipEndpoints)
            {
                if (tcpi.Port  == portToCheck)
                {
                    isAvailable = false;
                    break;
                }
            }
            _seleniumPort = portToCheck;
            return isAvailable;
        }

    }
}
